import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login/Login.vue'
import ForgetPwd from '../views/forgetPwd/ForgetPwd.vue'
import Home from '../views/home/Home.vue'
import Layout from '../layout/Layout.vue'
import Detail from '../views/detail/Detail.vue'
import Control from '../views/control/Control.vue'
import OperationLog from '../views/operationLog/OperationLog.vue'
import DataAnalysis from '../views/dataAnalysis/DataAnalysis.vue'
import GreenHouse from '../views/greenHouse/GreenHouse.vue'
import NotFound from '../views/NotFound.vue'
import Map from '../views/map/map.vue'
// 引入获取用户信息请求接口
import { getUserApi } from '../api/loginApi'
// 引入vuex文件
import store from '../store/index'

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: '/layout/home'
    },
    {
        path: '/layout',
        name: 'layout',
        component: Layout,
        children: [
            {
                path: 'home',
                name: 'home',
                component: Home,
                meta: { title: '首页' }
            },
            {
                path: 'detail',
                name: 'detail',
                component: Detail,
                meta: { title: '详情页' }
            },
            {
                path: 'control',
                name: 'control',
                component: Control,
                meta: { title: '控制页' }
            },
            {
                path: 'log',
                name: 'operationLog',
                component: OperationLog,
                meta: { title: '操作日志' }
            },
            {
                path: 'analysis',
                name: 'dataAnalysis',
                component: DataAnalysis,
                meta: { title: '数据分析' }
            },
            // {
            //     path: 'greenhouse',
            //     name: 'greenHouse',
            //     component: GreenHouse,
            //     meta: { title: '新建大棚' }
            // },
            {
                path: 'map',
                name: 'map',
                component: Map,
                meta: { title: '地图' }
            },
        ]
    },
    {
        path: '/login',
        name: 'login',
        component: Login
    },
    {
        path: '/forget',
        name: 'forget',
        component: ForgetPwd
    },
    {
        path: '*',
        component: NotFound
    }
]

// 动态路由数组【只分了用户和管理员，这里只设置了一个，管理员才能访问】
const routerAsync = [
    {
        path: 'greenhouse',
        name: 'greenHouse',
        component: GreenHouse,
        meta: { roles: ['管理员'], title: '新建大棚' }
    }
]

// 按照角色从动态路由数组里筛选符合角色的路由放到一个新数组里面
function getRouteFun(role, routerAsync) {
    return routerAsync.filter(item => item.meta.roles.includes(role))
}

// 白名单【已经在白名单的直接放行】
var whiteArr = ['/login', '/register', '/forget']

const router = new VueRouter({
    routes
})
router.beforeEach((to, from, next) => {
    // if (to.path === '/login' || to.path === '/forget') return next()
    // const tokenStr = window.sessionStorage.getItem('token')
    // if (!tokenStr) return next('/login')
    // next()
    var path = to.path
    const token = window.sessionStorage.getItem('token')
    if (token) {
        if (path == '/login') {
            next('/')
        } else {
            if (store.state.routes.length == 0) {
                getUserApi({ token }).then(res => {
                    if (res.code == 200) {
                        // console.log(res.data)
                        var role = res.data.rule
                        store.commit('setUser', res.data)
                        var userRoute = getRouteFun(role, routerAsync)
                        routes[1].children = routes[1].children.concat(userRoute)
                        var routesCopy = JSON.parse(JSON.stringify(routes))
                        routesCopy[1].children = routesCopy[1].children.filter(item => item.name != 'map')
                        store.commit('setRouter', routesCopy)
                        // 警告问题：解决vue动态添加路由，跳转页面时，页面路由重复
                        router.matcher = new VueRouter().matcher
                        router.addRoutes(routes)
                        next({...to, replace: true})
                    }
                })
            } else {
                next()
            }
        }
    } else {
        if (whiteArr.includes(path)) {
            next()
        } else {
            next('/login')
        }
    }
})
export default router